package com.daon.service.impl;

import com.daon.common.Const;
import com.daon.common.RequestHolder;
import com.daon.common.ServerResponse;
import com.daon.dao.SysNodeMapper;
import com.daon.param.SysNodeParam;
import com.daon.pojo.SysNode;
import com.daon.service.ISysNodeService;
import com.daon.util.BeanValidatorUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2019/2/26 7:24 PM
 * @Modified By
 */
@Service("iSysNodeService")
public class SysNodeServiceImpl implements ISysNodeService {

    @Autowired
    private SysNodeMapper sysNodeMapper;

    @Override
    public List<SysNode> getNodeList() {
        List<SysNode> nodeList = sysNodeMapper.getNodeAll();
        return nodeList;
    }
    @Override
    public ServerResponse save(SysNodeParam sysNodeParam) {
        BeanValidatorUtil.check(sysNodeParam);
        int nodePid = sysNodeParam.getNodePid();
        int nodeTopPid = getNodeTopPid(nodePid);
        SysNode sysNode = SysNode.builder().nodePid(nodePid).nodeName(sysNodeParam.getNodename())
                .nodeTopPid(nodeTopPid).nodeDesc(sysNodeParam.getNodeDesc())
                .nodeIcon(sysNodeParam.getNodeIcon()).nodeSort(sysNodeParam.getNodeSort())
                .nodeType(sysNodeParam.getNodetype()).nodeUrl(sysNodeParam.getNodeUrl())
                .createdAt(new Date()).updatedAt(new Date()).build();
        int rowCount = sysNodeMapper.insertSelective(sysNode);
        if(rowCount > 0) return ServerResponse.createBySuccessMessage("添加节点成功!");
        return ServerResponse.createByErrorMessage("添加节点失败!");
    }

    @Override
    public SysNode getNodeByNodeId(Integer nodeId){
        SysNode sysNode = sysNodeMapper.selectByPrimaryKey(nodeId);
        return sysNode;
    }

    @Override
    public ServerResponse update(SysNodeParam sysNodeParam){
        BeanValidatorUtil.check(sysNodeParam);
        SysNode sysNode = sysNodeMapper.selectByPrimaryKey(sysNodeParam.getNodeId());
        if(sysNode == null) return ServerResponse.createByErrorMessage("节点信息不存在！");
        int nodePid = sysNodeParam.getNodePid();
        int nodeTopPid = getNodeTopPid(nodePid);
        SysNode updateSysNode = SysNode.builder().nodeId(sysNodeParam.getNodeId()).nodePid(nodePid)
                .nodeName(sysNodeParam.getNodename())
                .nodeTopPid(nodeTopPid).nodeDesc(sysNodeParam.getNodeDesc())
                .nodeIcon(sysNodeParam.getNodeIcon()).nodeSort(sysNodeParam.getNodeSort())
                .nodeType(sysNodeParam.getNodetype()).nodeUrl(sysNodeParam.getNodeUrl())
                .createdAt(new Date()).updatedAt(new Date()).build();
        int updateCount = sysNodeMapper.updateByPrimaryKeySelective(updateSysNode);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("更新节点信息成功！");
        }
        return ServerResponse.createByErrorMessage("更新节点信息失败！");
    }

    @Override
    public ServerResponse deleteSysNodeById(int nodeId) {
        SysNode sysNode = sysNodeMapper.selectByPrimaryKey(nodeId);
        if(sysNode == null) return ServerResponse.createByErrorMessage("节点信息不存在！");
        List<SysNode> sysNodeByPid = sysNodeMapper.selectChildsById(nodeId);
        if(CollectionUtils.isNotEmpty(sysNodeByPid)) return ServerResponse.createByErrorMessage("当前节点下面有子节点，无法删除！");
        int resultCount = sysNodeMapper.deleteByPrimaryKey(nodeId);
        if(resultCount > 0) return ServerResponse.createBySuccessMessage("删除成功！");
        return ServerResponse.createByErrorMessage("删除失败！");
    }

    @Override
    public List<SysNode> getNodeListByCurrentUserId() {
        List<SysNode> sysNodeList = new ArrayList<>();
        int currentUserId = RequestHolder.getCurrentUser().getUserId();
        if(currentUserId == Const.User.SUPER_USER_ID){
            //超级管理员
            sysNodeList = sysNodeMapper.getNodeAll();
        }else{
            sysNodeList = sysNodeMapper.getNodeListByUserId(currentUserId);
        }
        HttpSession session = RequestHolder.getCurrentRequest().getSession();
        session.setAttribute(Const.CURRENT_USER_NODE, sysNodeList);
        return sysNodeList;
    }

    @Override
    public List<Object> getNodeChildNumList(List<Object> sysNodeTree) {
        for (Object n : sysNodeTree) {
            Map<String, Object> map = (Map<String, Object>) n;
            int onLevel = 0;
            for(Map.Entry<String, Object> m :map.entrySet()){
                //二级子节点
                if(m.getKey().equals("childList")){
                    List<Object> lists = (List<Object>) m.getValue();
                    if(lists.size() == 0){
                        onLevel = 1;
                        map.put("childrenCount", 1);
                    }else{
                        for(Object i:lists){
                            Map<String, Object> map2 = (Map<String, Object>) i;
                            for(Map.Entry<String, Object> m2 :map2.entrySet()){
                                //三级子节点
                                if(m2.getKey().equals("childList")) {
                                    List<Object> lists2 = (List<Object>) m2.getValue();
                                    if(lists2.size() == 0){
                                        map2.put("childrenCount", 1);
                                        onLevel = 1 + onLevel;
                                        map.put("childrenCount", onLevel);
                                    }else{
                                        map2.put("childrenCount", lists2.size());
                                        onLevel = lists2.size() + onLevel;
                                        map.put("childrenCount", onLevel);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return sysNodeTree;
    }

    private Integer getNodeTopPid(Integer nodeId){
        int nodeTopPid = 0;
        if(nodeId != 0){
            nodeTopPid = sysNodeMapper.getNodeTopPidByNodePid(nodeId);
            nodeTopPid = (nodeTopPid == 0 ?nodeId:nodeTopPid);
        }
        return nodeTopPid;
    }
}
